<template>
  <a-modal class="common-modal" :title="$t('sysManage.setRoleRights')" :footer="null" width="1000px" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel" :maskClosable="false" style="top: 5%">
    <div class="p-20">
      <a-table :columns="columns" :dataSource="dataSource" :loading="loading" rowKey="id" childrenColumnName="null" :pagination="false" :scroll="{ y: '60vh' }" :defaultExpandAllRows="true">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'label'">
            <a-checkbox v-model:checked="record.menu1Checked" @change="(e) => level1Change(e, record)" :disabled="isDetails">
              {{ $t(`menu.${record.permission}`) }}
            </a-checkbox>
          </template>
        </template>

        <template #expandedRowRender="{ record, index }">
          <a-table :key="index" :columns="insideColumns" :dataSource="record.children" :loading="loading" rowKey="id" :showHeader="false" childrenColumnName="null" :pagination="false" bordered>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'label'">
                <a-checkbox v-model:checked="record.menu2Checked" @change="(e) => level2Change(e, record, index)" :disabled="isDetails">
                  {{ record.isLevel3Menu ? $t(`menu.${record.parentLabel}`)  : $t(`menu.${record.permission}`) }}
                </a-checkbox>
              </template>
              <template v-if="column.key === 'Level3'">
                <a-checkbox v-if="record.isLevel3Menu" v-model:checked="record.menu3Checked" @change="(e) => level3Change(e, record, index)" :disabled="isDetails">
                  {{ $t(`menu.${record.permission}`) }}
                </a-checkbox>
              </template>
              <template v-if="column.key === 'operate'">
                <a-checkbox-group v-model:value="record.operateList" :disabled="isDetails" >
                  <a-checkbox v-for="(item, i) in record.children" :key="i" :value="item.id">{{$t(`chinese.${item.label}`)}}</a-checkbox>
                </a-checkbox-group>
              </template>
            </template>
          </a-table>
        </template>
      </a-table>
    </div>
    <div class="common-modal-footer">
      <a-button @click="handleCancel" class="cancel">{{$t('common.cancel')}}</a-button>
      <a-button @click="handleOk" type="primary" class="confirm" v-if="!isDetails">
        {{$t('common.ok')}}
      </a-button>
    </div>
  </a-modal>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue'
import { cloneDeep } from 'lodash'
import { message } from 'ant-design-vue'
import axios from '@/utils/request'
import { store } from '@/store'
import i18n from '@/locales/index' 
const { t } = i18n.global
const emits = defineEmits(['ok'])
let visible = ref(false)
let confirmLoading = ref(false)
let loading = ref(false)
let columns = ref([
  {
    title: t('sysManage.menu'),
    dataIndex: 'label',
    key: 'label',
    width: 200,
  },
  {
    title: t('sysManage.threeMenu'),
    dataIndex: 'Level3Menu',
    key: 'Level3Menu',
    width: 200,
  },
  { title: t('sysManage.optRights'), dataIndex: 'operate', key: 'operate' },
])
let insideColumns = ref([
  {
    title: t('sysManage.menu'),
    dataIndex: 'label',
    key: 'label',
    width: 200,
    customCell: (record) => ({
      rowSpan: record && record.rowSpan,
    }),
  },
  {
    title: t('sysManage.threeMenu'),
    dataIndex: 'Level3',
    key: 'Level3',
    width: 200,
  },
  { title: t('sysManage.optRights'), dataIndex: 'operate', key: 'operate' },
])
let dataSource = ref([])
let recordInfo = ref({})
let isDetails = ref(false)
const allMenuList = computed(() => {
  return store.state.normalData.allMenuList
})
const open = (record, isView = false) => {
  isDetails.value = isView
  visible.value = true
  recordInfo.value = record
  initTableData()
}

const handleOk = async () => {
  const params = {
    menuIds: getParams(),
    id: recordInfo.value.id,
  }
  confirmLoading.value = true
  const res = await axios.postAction('/api/system/role/edit-role-permission', params)
  if (res.success) {
    message.success(res.msg || t('common.successTip'))
    emits('ok')
    visible.value = false
  }

  confirmLoading.value = false
}

const getParams = () => {
  let tableData = dataSource.value
  let checkedValue = tableData.reduce((prev, next) => {
    let allChecked = []
    if (next.menu1Checked) allChecked.push(next.id)
    next.children &&
      next.children.forEach((item) => {
        if (item.isLevel3Menu) {
          item.menu3Checked && allChecked.push(item.id)
          item.menu2Checked && allChecked.push(item.parentId)
        } else {
          item.menu2Checked && allChecked.push(item.id)
        }
        // console.log('!!!!!!!', item.operateList);
        allChecked.push(...item.operateList)
      })
    return prev.concat(allChecked)
  }, [])
  return Array.from(new Set(checkedValue))
}

const handleCancel = () => {
  visible.value = false
}

const level1Change = (e, record) => {
  let checked = e.target.checked
  record.children &&
    record.children.forEach((item) => {
      item.menu2Checked = checked
      if (item.isLevel3Menu) {
        item.menu3Checked = checked
        level4Change(item)
      }
      if (!item.isLevel3Menu){
        let tmpArr1 = []
        item.children && item.children.forEach(item1=>{
          if ( item.menu2Checked &&  item.id == item1.parentId ){
            tmpArr1.push(item1.id)
          }
        })
        item.operateList = tmpArr1
      }

    })
}
const level2Change = (e, record, innerIndex) => {
  let checked = e.target.checked
  let data = dataSource.value[innerIndex]
  record.isLevel3Menu &&
    data.children.forEach((item) => {
      if (item.parentId == record.parentId) {
        item.menu3Checked = checked
        item.menu2Checked = checked
        level4Change( item )
      }
    })

  //没有3级菜单 2级直接控制4级
  if (!record.isLevel3Menu ){
    let tmpArr1 = []
    record.children.forEach(item1=>{
      if ( record.menu2Checked &&  record.id == item1.parentId ){
        tmpArr1.push(item1.id)
      }
    })
    record.operateList = tmpArr1
  }
  changeLeve1Status(data)
}

const changeLeve1Status = (data) => {
  let level2AllSelected = data.children.some((item) => item.menu2Checked)
  data.menu1Checked = level2AllSelected
}

const level3Change = (e, record, innerIndex) => {
  let data = dataSource.value[innerIndex]
  if (record.isLevel3Menu) {
    const sameParentAry = data.children.filter(
      (item) => item.parentId == record.parentId
    )
    sameParentAry.forEach((item) => {
      item.menu2Checked = sameParentAry.some((el) => el.menu3Checked)
    })
  }
  changeLeve1Status(data)
  level4Change( record )
}

// 选中3级菜单 对应操作权限要选中
const level4Change = ( record ) => {
  if (record.children){
    let tmpArr = []
    record.children.forEach(item=>{
      if ( record.menu3Checked && record.id == item.parentId ){
        tmpArr.push(item.id)
      }
    })
    record.operateList = tmpArr
  }
}

const initTableData = () => {
  let menuIds = recordInfo.value.menuIds || []
  let data = cloneDeep(allMenuList.value)
  data.forEach((item) => {
    item.menu1Checked = menuIds.includes(item.id)
    if (item.children) item.children = initMenu(item.children, menuIds)
  })
  dataSource.value = data
}

const initMenu = (level2Ary, menuIds) => {
  const list = level2Ary.reduce((prev, next) => {
    if (next.type == 0) {
      next.children?.length && next.children.forEach((item, index) => {
        item.parentLabel = next.permission
        item.isLevel3Menu = true
        item.rowSpan = index == 0 ? next.children.length : 0
        item.menu3Checked = menuIds.includes(item.id)
        item.menu2Checked = menuIds.includes(item.parentId)

        item.operateList = item.children
          ? item.children.filter((i) => menuIds.includes(i.id)).map((i) => i.id)
          : []
      })
      return prev.concat(next.children)
    } else if (next.type == 1) {
      next.rowSpan = 1
      next.menu2Checked = menuIds.includes(next.id)
      next.operateList = next.children
        ? next.children.filter((i) => menuIds.includes(i.id)).map((i) => i.id)
        : []
      return next.visible ? prev.concat([next]) : prev
    }
  }, [])
  return list
}
defineExpose({
  open,
})

onMounted(async () => {
  loading.value = true
  if (!allMenuList.value.length) await store.dispatch('getAllMenu')
  loading.value = false
  initTableData()
})
</script>
